//////////////////////////////////
//
// ADS8344 .c TI 8 channel ADC
//
//////////////////////////////////

#include "p18f26k22.h"
#include <GenericTypeDefs.h>

#include "ads8344.h"

//configured for use in external mode
//SPI clock controls Taq (4 Clocks) and T converison (16 clocks)
void ads8344_comms_config(void)
{
        //port pin config
    CS1_LAT = 0b1;      //set CS high
    CS1_TRIS = 0b0;     //CS is an input
    CLK1_TRIS = 0b0;    //output clock
    DIN1_TRIS = 0b1;    //data input
    DOUT1_TRIS = 0b0;   //data output
    ANSELA = 0x00;
    ANSELB = 0x00;
    ANSELC = 0x00;

    PIR1bits.SSP1IF = 0b0;
    PIE1bits.SSP1IE = 0b0;
    IPR1bits.SSP1IP = 0b1;

    SSP1STATbits.CKE = 0b1;
    SSP1STATbits.SMP = 0b0;
    SSP1CON1bits.CKP = 0b0;
    SSP1CON1bits.SSPM = 0b0010;    //Master mode Fosc/64 ~ 2Mhz
    SSP1CON1bits.SSPEN = 0b1;

    //timer 4 interrupt
    TMR4                = 0;        //reset
    PR4                 = 36;        //Timer 4 period - period of 7812Hz - 36
    T4CONbits.T4CKPS    = 0b10;     //1:16 Pre-scaler (post scaler only relevent to TxIF 250kHz
    T4CONbits.T4OUTPS   = 0b0011;   //1:4 post scaler IF post scaler
    PIR5bits.TMR4IF     = 0b0;      //clear interrupt flag
    PIE5bits.TMR4IE     = 0b1;      //Enable interrupt
    IPR5bits.TMR4IP     = 0b1;      //High priority
    T4CONbits.TMR4ON    = 0b1;      //Switch Timer 2 ON
}

UINT16 read_ads8344(UINT8 channel_num)
{
	UINT16 dummy;
    UINT8 command_byte = 0x87;  //initialise with start bit set high
                                //external clock mode
                                //single ended
    UINT16 data;
    UINT16 printfData;
    data = 0;
	dummy = SSP1BUF;
    CS1_LAT = 0b0;
    command_byte |= ((channel_num & 0x07) << 4);
    PIR1bits.SSP1IF = 0b0;
    SSP1BUF = command_byte;
    while(!PIR1bits.SSP1IF){}
	dummy = SSP1BUF;
    PIR1bits.SSP1IF = 0b0;
    SSP1BUF = 0x00;
    while(!PIR1bits.SSP1IF){}
	dummy = SSP1BUF;
    //printfData = dummy;
    PIR1bits.SSP1IF = 0b0;
    data += (dummy << 9);
    SSP1BUF = 0x00;
    while(!PIR1bits.SSP1IF){}
	dummy = SSP1BUF;
    //printfData += dummy;
    data += (dummy << 1);
    PIR1bits.SSP1IF = 0b0;
    SSP1BUF = 0x00;
    while(!PIR1bits.SSP1IF){}
	dummy = SSP1BUF;
    data += (dummy >> 7);
    //printfData += dummy;
    PIR1bits.SSP1IF = 0b0;
    CS1_LAT = 0b1;
    //set CS high
    return data;
}